import { useState, useEffect } from "react";
import api from "../request";
import "./Poem.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { textToParagraphs } from "../utils";
import { Poem as PoemEntity } from "poetry";
import useGlobalContext from "../GlobalContext";
import { Link, useNavigate } from "react-router-dom";
import { useCollectionModal } from "../Modal/CollectionModal";
import PoemDetailResponseDTO from "poetry";
import { Badge, Placeholder } from "react-bootstrap";


/**
 * @param {object} props
 * @param {string?} props.poemId
 * @param {PoemEntity?} props.poem
 * @param {boolean} [props.showLikeCount=true]
 * @param {boolean} [props.showCollectCount=true]
 * @param {boolean} [props.showTranslation=true]
 * @param {boolean} [props.showAnnotation=true]
 * @param {boolean} [props.showAppreciation=true]
 * @param {boolean} [props.linkOnTitle=false]
 * @returns 
 */
function Poem({
    poemId,
    poem,
    showLikeCount = true,
    showCollectCount = true,
    showTranslation = true,
    showAnnotation = true,
    showAppreciation = true,
    linkOnTitle = false
}) {
    /** @type {[PoemDetailResponseDTO,]} */
    const [poemData, setPoemData] = useState(null);
    const [context, dispatch] = useGlobalContext();
    const navigate = useNavigate();
    const [CollectionModal, show, hide] = useCollectionModal(() => fetchData(poemData.id));

    function fetchData(poemId) {
        return api.getPoemById(poemId, (err, data, res) => {
            if (err) {
                console.error(err);
                return;
            }
            setPoemData(data.data);
        });
    }

    useEffect(() => {
        if (poem)
            setPoemData(poem);
        else if (poemId) {
            fetchData(poemId);
        } else 
            throw new Error("Poem component must have either poemId or poem prop.");

    }, [poemId, poem]);

    function handleLike() {
        if (!context.user.id)
            navigate('/login');
        api.likePoem({ poemId: poemData.id, liked: !poemData.liked }, (err, data, res) => {
            if (err) throw err;
            // let newLikeCount = poemData.liked ? poemData.likeCount - 1 : poemData.likeCount + 1;
            // setPoemData({ ...poemData, liked: !poemData.liked, likeCount: newLikeCount });
            fetchData(poemData.id);
        });
    }

    function handleCollect() {
        if (!context.user.id)
            navigate('/login');
        show(poemData.id);
        ;
    }

    let content;
    if (poemData) {
        content = (
            <div className="poem">
                <div className="poem-body">
                    {linkOnTitle ? 
                        <h1 className="poem-title"><b><Link to={"/poem/" + poemData.id}>{poemData.title}</Link></b></h1>
                      : <h1 className="poem-title"><b>{poemData.title}</b></h1>
                    }
                    <p className="poem-author text-muted">【{poemData.author.dynasty}】{poemData.author.name}</p>
                    {poemData.tags && (
                        <div className="poem-tags">
                            {poemData.tags.map((tag, index) => (
                                <Badge key={index} bg="secondary" className="me-1" as={Link} to={'/tag/' + tag.id}>{tag.name}</Badge>
                            ))}
                        </div>
                    )}
                    <br />
                    {
                        poemData.content.split("\n").map((line, index) => {
                            return <p className="poem-body" key={index}>{line}</p>;
                        })
                    }
                </div>
                <div className="poem-toolbar fs-3">
                    <button onClick={handleLike} className={poemData.liked && "activated"}>
                        <FontAwesomeIcon icon="thumbs-up" />
                        {showLikeCount && <span>{poemData.likeCount}</span>}
                    </button>
                    <button onClick={handleCollect} className={"ms-3 " + (poemData.collected && "activated")}>
                        <FontAwesomeIcon icon="star" />
                        {showCollectCount && <span>{poemData.collectionCount}</span>}
                    </button>
                </div>
                <div className="poem-appendix">
                    {
                        (showTranslation && poemData.translation) &&
                        <div className="poem-translation">
                            <h3>译文</h3>
                            {textToParagraphs(poemData.translation)}
                        </div>
                    }
                    {
                        (showAnnotation && poemData.annotation) &&
                        <div className="poem-annotation">
                            <h3>注解</h3>
                            <ol>
                                {
                                    poemData.annotation.split('\n')
                                        .map((line, index) => <li key={index}>{line}</li>)
                                }
                            </ol>
                        </div>
                    }
                    {
                        (showAppreciation && poemData.appreciation) &&
                        <div className="poem-appreciation">
                            <h3>赏析</h3>
                            {textToParagraphs(poemData.appreciation)}
                        </div>
                    }
                </div>
                {CollectionModal}
            </div>
        );
    } else {
        content = (
            <Placeholder as="div" animation="wave" className="col-sm-11">
                <div className="mb-3 mx-auto text-center col-lg-6">
                    <Placeholder as="h1" xs={4}></Placeholder>
                    <Placeholder as="span" className="ms-3" xs={1}></Placeholder>
                </div>
                <div className="mb-3 mx-auto text-center col-lg-6">
                    <Placeholder as="p" xs={12}></Placeholder>
                    <Placeholder as="p" xs={12}></Placeholder>
                    <Placeholder as="p" xs={12}></Placeholder>
                    <Placeholder as="p" xs={12}></Placeholder>
                </div>
                <div className="mb-3 col-lg-12">
                    <Placeholder as="h3" xs={1}></Placeholder>
                    <Placeholder as="p" xs={12}></Placeholder>
                    <Placeholder as="p" xs={12}></Placeholder>
                    <Placeholder as="p" xs={12}></Placeholder>
                </div>
                <div className="mb-3 col-lg-12">
                    <Placeholder as="h3" xs={1}></Placeholder>
                    <Placeholder as="ol" xs={12}>
                        <Placeholder as="li" xs={4}></Placeholder>
                        <Placeholder as="li" xs={4}></Placeholder>
                        <Placeholder as="li" xs={4}></Placeholder>
                    </Placeholder>
                </div>
            </Placeholder>
        );
    }

    return content;
}

export default Poem;
